<template>
  <div class="config-settings">
    <div class="header">
      <h2>配置设置初始化</h2>
      <p class="api-info">接口地址: http://47.109.177.78:6300/api/common/config/initConfigSettings (直连模式)</p>
      <div class="mode-info">
        <span class="direct-badge">⚡ 直连模式</span>
        <span>直接访问 API 无需代理</span>
        <span class="auth-badge">🔐 已配置认证</span>
      </div>
    </div>

    <div class="main-container">
      <!-- 操作区域 -->
      <div class="action-panel">
        <button 
          @click="initializeConfig" 
          :disabled="isLoading"
          class="init-button"
        >
          {{ isLoading ? '初始化中...' : '初始化配置' }}
        </button>
        <button 
          @click="clearResults" 
          class="clear-button"
          :disabled="isLoading"
        >
          清空结果
        </button>
      </div>

      <!-- 响应结果显示区域 -->
      <div class="result-container">
        <h3>响应结果</h3>
        <div v-if="isLoading" class="loading-indicator">
          <div class="spinner"></div>
          <span>正在请求配置初始化...</span>
        </div>
        
        <div v-if="response" class="response-section">
          <div class="response-header">
            <span :class="['status-badge', response.success ? 'success' : 'error']">
              {{ response.success ? '成功' : '失败' }}
            </span>
            <span class="timestamp">{{ response.timestamp }}</span>
          </div>
          
          <div class="response-content">
            <h4>响应内容:</h4>
            <pre class="json-content">{{ formatJson(response.data) }}</pre>
          </div>
          
          <div v-if="response.error" class="error-content">
            <h4>错误信息:</h4>
            <pre class="error-text">{{ response.error }}</pre>
          </div>
        </div>

        <div v-if="!response && !isLoading" class="empty-state">
          <p>点击"初始化配置"按钮开始请求</p>
        </div>
      </div>

      <!-- 请求详情 -->
      <div class="request-details" v-if="showDetails">
        <h3>请求详情</h3>
        <div class="detail-item">
          <strong>请求方法:</strong> GET
        </div>
        <div class="detail-item">
          <strong>请求地址:</strong> {{ apiUrl }}
        </div>
        <div class="detail-item">
          <strong>请求头:</strong>
          <pre class="headers-content">{{ formatJson(requestHeaders) }}</pre>
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="controls">
        <button @click="showDetails = !showDetails" class="detail-toggle">
          {{ showDetails ? '隐藏请求详情' : '显示请求详情' }}
        </button>
      </div>
    </div>

    <!-- 状态提示 -->
    <div v-if="statusMessage" class="status-message" :class="statusMessage.type">
      {{ statusMessage.text }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'

interface ApiResponse {
  success: boolean
  data: any
  error?: string
  timestamp: string
  status?: number
}

interface StatusMessage {
  type: 'success' | 'error' | 'warning' | 'info'
  text: string
}

// 响应式数据
const isLoading = ref(false)
const response = ref<ApiResponse | null>(null)
const statusMessage = ref<StatusMessage | null>(null)
const showDetails = ref(false)

// API配置
const apiUrl = 'http://47.109.177.78:6300/api/common/config/initConfigSettings'
const authToken = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3NTY4MDc1MzMsImlzcyI6InRpZ3Nob3AiLCJzdWIiOiIxMzI1ODM2NTQyMSIsImV4cCI6MTc1OTM5OTUzMywidXNlcm5hbWUiOiIxMzI1ODM2NTQyMSIsImlzQWRtaW4iOmZhbHNlLCJ1c2VySWQiOjd9.ZdjwTTd7h7jfAgJvDwe7lGoqtU1MEEziBDA6TpZFdE_t2RV6JyU9wKPkHmcCtSbAnx7DMU0QlhNkxeG7C4Y33w'

// 请求头配置
const requestHeaders = reactive({
  'Content-Type': 'application/json',
  'Authorization': authToken
})

// 初始化配置
const initializeConfig = async () => {
  if (isLoading.value) return

  isLoading.value = true
  statusMessage.value = null
  
  try {
    console.log('发送配置初始化请求:', apiUrl)
    
    const startTime = Date.now()
    const fetchResponse = await fetch(apiUrl, {
      method: 'GET',
      headers: requestHeaders,
      mode: 'cors' // 明确指定CORS模式
    })

    const endTime = Date.now()
    const duration = endTime - startTime

    console.log('响应状态:', fetchResponse.status)
    console.log('请求耗时:', duration + 'ms')

    let responseData: any
    const contentType = fetchResponse.headers.get('content-type')
    
    if (contentType && contentType.includes('application/json')) {
      responseData = await fetchResponse.json()
    } else {
      responseData = await fetchResponse.text()
    }

    response.value = {
      success: fetchResponse.ok,
      data: responseData,
      timestamp: new Date().toLocaleString(),
      status: fetchResponse.status
    }

    if (fetchResponse.ok) {
      statusMessage.value = {
        type: 'success',
        text: `配置初始化成功 (${duration}ms)`
      }
    } else {
      response.value.error = `HTTP ${fetchResponse.status}: ${fetchResponse.statusText}`
      statusMessage.value = {
        type: 'error',
        text: `请求失败: ${fetchResponse.status} ${fetchResponse.statusText}`
      }
    }

  } catch (error) {
    console.error('请求失败:', error)
    
    let errorMessage = '未知错误'
    if (error instanceof TypeError && error.message.includes('fetch')) {
      errorMessage = '网络连接失败，请检查网络状态和服务器是否可访问'
    } else if (error instanceof Error) {
      errorMessage = error.message
    }

    response.value = {
      success: false,
      data: null,
      error: errorMessage,
      timestamp: new Date().toLocaleString()
    }

    statusMessage.value = {
      type: 'error',
      text: `请求失败: ${errorMessage}`
    }
  } finally {
    isLoading.value = false
    
    // 5秒后清除状态消息
    setTimeout(() => {
      statusMessage.value = null
    }, 5000)
  }
}

// 清空结果
const clearResults = () => {
  response.value = null
  statusMessage.value = null
}

// 格式化JSON
const formatJson = (data: any): string => {
  if (data === null || data === undefined) {
    return 'null'
  }
  if (typeof data === 'string') {
    return data
  }
  try {
    return JSON.stringify(data, null, 2)
  } catch {
    return String(data)
  }
}
</script>

<style scoped>
.config-settings {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border-radius: 12px;
}

.header h2 {
  margin: 0 0 10px 0;
  font-size: 1.8rem;
}

.api-info {
  margin: 0 0 15px 0;
  font-size: 0.9rem;
  opacity: 0.9;
  word-break: break-all;
}

.mode-info {
  display: flex;
  align-items: center;
  gap: 15px;
  justify-content: center;
  margin-top: 15px;
  font-size: 0.85rem;
}

.direct-badge {
  background: rgba(76, 175, 80, 0.3);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
}

.auth-badge {
  background: rgba(76, 175, 80, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
}

.main-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.action-panel {
  padding: 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  gap: 15px;
  justify-content: center;
}

.init-button {
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.init-button:hover:not(:disabled) {
  background: #45a049;
}

.init-button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.clear-button {
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.clear-button:hover:not(:disabled) {
  background: #5a6268;
}

.clear-button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.result-container {
  padding: 20px;
}

.result-container h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 20px;
  text-align: center;
  color: #666;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #4CAF50;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.response-section {
  border: 1px solid #e9ecef;
  border-radius: 8px;
  overflow: hidden;
}

.response-header {
  background: #f8f9fa;
  padding: 12px 15px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.85rem;
  font-weight: bold;
}

.status-badge.success {
  background: #d4edda;
  color: #155724;
}

.status-badge.error {
  background: #f8d7da;
  color: #721c24;
}

.timestamp {
  font-size: 0.85rem;
  color: #666;
}

.response-content,
.error-content {
  padding: 15px;
}

.response-content h4,
.error-content h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.json-content {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 12px;
  margin: 0;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.error-text {
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  padding: 12px;
  margin: 0;
  color: #721c24;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}

.request-details {
  padding: 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.request-details h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.detail-item {
  margin-bottom: 10px;
  font-size: 0.9rem;
}

.headers-content {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 8px;
  margin: 5px 0 0 0;
  font-family: 'Courier New', monospace;
  font-size: 0.85rem;
  overflow-x: auto;
}

.controls {
  padding: 15px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
  text-align: center;
}

.detail-toggle {
  background: #17a2b8;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.detail-toggle:hover {
  background: #138496;
}

.status-message {
  padding: 12px 16px;
  border-radius: 8px;
  margin-top: 15px;
  font-size: 0.9rem;
}

.status-message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.status-message.warning {
  background: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
}

.status-message.info {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #bee5eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .config-settings {
    padding: 10px;
  }
  
  .action-panel {
    flex-direction: column;
    align-items: center;
  }
  
  .mode-info {
    flex-direction: column;
    gap: 8px;
  }
  
  .response-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}
</style>